import json
import logging

from ocup.constants import DATABASE

logger = logging.getLogger("ocup")


class DataBase(object):
    def __init__(self):
        self._db = DATABASE
        self._data = {}

    def _read(self):
        try:
            with open(self._db) as f:
                self._data = json.load(f)
        except IOError as e:
            logger.error(e)
            raise e

    def _write(self):
        try:
            with open(self._db, 'w') as f:
                json.dump(self._data, f, indent=4)
        except IOError as e:
            logger.error(e)
            raise e

    def get(self, attr):
        self._read()
        return self._data.get(attr, None)

    def set(self, attr, value):
        self._read()
        self._data[attr] = value
        self._write()


db = DataBase()
